# -*- coding: utf-8 -*- 
# @Time : 2021/3/29 21:43 
# @Author : Dong 
# @File : demo_one.py
import re
import time
from multiprocessing import Pool
from pyquery import PyQuery as pq
from selenium import webdriver
from requests.exceptions import RequestException   # 抓取报错
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import config
import pymongo

# mongodb 配置
client = pymongo.MongoClient(config.MONGO_URL)
db = client[config.MONGO_DB]


# .PhantomJS 是后台运行 需要另外下载一个驱动 还有一些配置在config中
# browser2 = webdriver.PhantomJS(service_args=config.SERVICE_ARGS)
# browser2.set_window_size(1400,900)  # 窗口大小

browser = webdriver.Chrome()

# chrome_option = webdriver.ChromeOptions()
# chrome_option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 以开发者模式
# browser = webdriver.Chrome(options=chrome_option)

wait = WebDriverWait(browser, 20)  # 等待加载时间

def search():

    try:
        browser.get("http://taobao.com")
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#q")))  # 获取搜索框
        submit= wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#J_TSearchForm > div.search-button > button')))  # 获取搜索按钮
        input.send_keys(config.KEYWORD)  # 输入要搜索的
        submit.click()
        time.sleep(3)
        parse_page()
        total_page = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.total')))  # 获取页面下的总数
        return total_page.text
    except RequestException as e:
        print(e)
        return search()

def next_page(page):
    # 第几页
    try:
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input")))
        '''#mainsrp-pager > div > div > div > div.form > input'''
        # 点击确定
        submit = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')))
        input.clear()
        input.send_keys(page)  # 输入第几页
        submit.click()
        # 判断page与高亮的地方是否一致
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page)))
        parse_page()
    except RequestException as e:
        print(e)
        return next_page(page)

def parse_page():
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))  # 选中所有的item
    html = browser.page_source # 获取整个页面
    doc = pq(html)
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        product = {
            'image':item.find('.pic .img').attr('src'),
            'price':item.find('.price').text(),
            'pay_count': item.find('.deal-cnt').text()[:-3],
            'title': item.find('.title').text(),
            'shop': item.find('.shop').text(),
            'location': item.find('.location').text()
        }
        save_to_mongo(product)


def save_to_mongo(result):
    try:
        if db[config.MONGO_TABLE].insert(result):
            print('存储成功',result)
    except Exception as e:
        print('存储错误',result)

def main():
    total = search()
    print(total)
    total_page = int(re.compile('(\d+)').search(total).group(1))
    for i in range(2,total_page + 1):
        next_page(i)
    browser.close()

if __name__ == '__main__':
    main()